package com.gec.teams.wechat.config.shiro;

/**
 * 功能：
 * 作者：YumTea
 * 日期：2024/6/14 10:41
 */

import com.gec.teams.wechat.common.ThreadLocalToken;
import com.gec.teams.wechat.mapper.TbUserMapper;
import com.gec.teams.wechat.pojo.TbUser;
import com.gec.teams.wechat.util.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class OAuth2Realm extends AuthorizingRealm {
    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private TbUserMapper userMapper;

    //验证token 是否合法
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    //授权(验证权限时调用)
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection collection) {
         TbUser user = (TbUser) collection.getPrimaryPrincipal();
         //获取权限
        Set<String> permissions = userMapper.getsearchUserPermissions(user.getId());
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
            info.setStringPermissions(permissions);

        return info;
    }

    //认证(验证登录时调用)
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 获取token字符串
         String t = (String) token.getPrincipal();
        int userId = jwtUtil.getUserId(t);
        //获取状态为1的用户信息
        TbUser user = userMapper.selectByPrimaryKey(userId);
        if(user==null) throw new LockedAccountException("哦吼,账号被动了捏,试试联系管理员吧");
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,t,getName());
        return info;
    }


}